<template>
  <div class="vue-editor">
    <ckeditor id="editor" :editor="editor" @ready="onReady" @input="changeContent" v-model="editorData" :config="editorConfig"></ckeditor>
  </div>
</template>

<script>
  import CKEditor from '@ckeditor/ckeditor5-build-decoupled-document'; //CKEditor 编辑器
  import '@ckeditor/ckeditor5-build-decoupled-document/build/translations/ko.js'; //CKEditor韩文语言包
  import {
    uploadFile,
    deleteFile
  } from '@/api/files'
  export default {
    name: 'editor',
    props: ["contents"],
    data() {
      return {
        editor: CKEditor,
        editorData: this.contents,
        oldValue: '',
        editorConfig: {
          removePlugins: [],
          language: 'ko',
        },
      }
    },
    watch: {
      contents(val) {
        this.editorData = val; //监听修改 同步到editorData
      }
    },
    methods: {
      changeContent() {
        this.$emit('changeContent', this.editorData);
      },
      onReady(editor) {
        const self = this;
        class UploadAdapter {
          constructor(loader) {
            self.loader = loader;
          }
          upload() {
            return new Promise((resolve, reject) => {
              const genericErrorText = `can't upload image size more than 5Mb`;
              let size = self.loader.file.size;
              if (size / 1024 > 1024 * 1) {
                self.$message({
                  message: genericErrorText
                });
                return reject(genericErrorText);
              }
              let uloadImageData = new FormData();
              uloadImageData.append('imageFile', self.loader.file);
              self.fullscreenLoading = true;
              uploadFile(uloadImageData).then(res => {
                self.fullscreenLoading = false;
                if (res) {
                  resolve({
                    default: process.env.BASE_API + res.data.url
                  });
                } else {
                  self.$message({
                    message: 'can not upload file: ' + self.loader.file.name
                  });
                }
              })
            })
          }
          abort() {}
        }
        CKEditor.builtinPlugins.map(plugin => plugin.pluginName);
        // Insert the toolbar before the editable area. 初始化编辑器 加载toolbarUI
        editor.ui.view.editable.element.parentElement.insertBefore(
          editor.ui.view.toolbar.element,
          editor.ui.view.editable.element
        );
        editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
          return new UploadAdapter(loader)
        }
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .upload-files {
    width: 500px;
  }
  .ck-content {
    max-height: 700px;
  }
</style>
